package manager;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import model.Dish;
import util.FileUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 菜品管理类，支持增删改查，持久化存储到JSON文件
 */
public class DishManager {

    private static final String DISH_FILE = "data/dishes.json"; // 菜品数据文件路径
    private List<Dish> dishList;
    private Gson gson;

    public DishManager() {
        gson = new Gson();
        loadDishes();
    }

    private void loadDishes() {
        String json = FileUtil.readFile(DISH_FILE);
        if (json.isEmpty()) {
            dishList = new ArrayList<>();
            saveDishes();
        } else {
            Type type = new TypeToken<List<Dish>>(){}.getType();
            dishList = gson.fromJson(json, type);
            if (dishList == null) dishList = new ArrayList<>();
        }
    }

    private void saveDishes() {
        String json = gson.toJson(dishList);
        FileUtil.writeFile(DISH_FILE, json);
    }

    /**
     * 获取所有菜品
     */
    public List<Dish> getAllDishes() {
        return dishList;
    }

    /**
     * 根据ID查找菜品
     */
    public Dish getDishById(int id) {
        for (Dish d : dishList) {
            if (d.getId() == id) return d;
        }
        return null;
    }

    /**
     * 添加新菜品，ID自动递增
     */
    public void addDish(String name, double price) {
        int newId = 1;
        if (!dishList.isEmpty()) {
            newId = dishList.get(dishList.size()-1).getId() + 1;
        }
        dishList.add(new Dish(newId, name, price));
        saveDishes();
    }

    /**
     * 修改菜品信息（接口调用名为 editDish）
     */
    public boolean editDish(int id, String newName, double newPrice) {
        for (Dish d : dishList) {
            if (d.getId() == id) {
                d.setName(newName);
                d.setPrice(newPrice);
                saveDishes();
                return true;
            }
        }
        return false;
    }

    /**
     * 删除菜品
     */
    public boolean deleteDish(int id) {
        for (Dish d : dishList) {
            if (d.getId() == id) {
                dishList.remove(d);
                saveDishes();
                return true;
            }
        }
        return false;
    }
}
